package com.momoback.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.momoback.api.service.MiniProgramService;
import com.momoback.entity.Result;
import com.momoback.entity.UserInfo;
import com.momoback.entity.WechatLoginRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/app")
public class MiniProgramController {

    @Autowired
    private MiniProgramService miniProgramService;


    @ResponseBody
    @PostMapping(value = "/sendCode")
    public Result sendPhoneNumber(@RequestBody JSONObject phone) {
        if (StringUtils.isEmpty(phone)) {
            throw new RuntimeException("请输入手机号码!");
        }
        String registerId = miniProgramService.getRegisterId();
        System.out.println(registerId);
        miniProgramService.createVerifyCode(phone.getString("phone"));
        if (registerId != null) {
            JSONObject jsonId = new JSONObject();
            jsonId.put("id", registerId);
            return Result.builder().code(200).message("success").data(jsonId).build();
        }
        return Result.builder().code(500).message("failed").data(null).build();
    }


    @ResponseBody
    @PostMapping("/login")
    public Result getUserInfo(@RequestBody WechatLoginRequest request) {
        try {
            if (StringUtils.isEmpty(request.getVerifyCode())) {
                throw new RuntimeException("请输入验证码");
            }
            JSONObject userInfo = miniProgramService.verifyCodeAndLogin(request);
            if (userInfo != null) {
                return Result.builder().data(userInfo).message("success").code(200).build();
            }

        } catch (Exception e) {
            System.out.println(e);
        }
        return Result.builder().code(500).message("登陆失败，请重新登陆").build();
    }

    @ResponseBody
    @PostMapping(value = "/upload")
    public Map<String, String> uploadFile(@RequestPart("file") MultipartFile file,@RequestPart("chatId") String chatId) {


        try {
            // 获取文件名
            String fileName = file.getOriginalFilename();
            // 指定上传文件的存储路径
            String uploadDir = "C:\\Users\\clps\\Desktop\\project\\momo-back\\src\\main\\resources\\";
            File destFile = new File(uploadDir + fileName);

            // 保存文件到指定路径
            file.transferTo(destFile);

            Map<String, String> result = miniProgramService.handleFile(destFile.getAbsolutePath(), file.getOriginalFilename(),chatId);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }
}